import { defineStore } from 'pinia'
import { TokenUtils } from '@/utils/auth/index'
import { login, logout, getInfo, getAuth } from '@/api/api-login'
import { ElMessage } from 'element-plus'

// import 
const useUserStore = defineStore(
  'user',
  {
    state: () => ({
      token: TokenUtils.getAuthorization(),
      name: '',
      avatar: '',
      roles: [],
      permissions: [],
      userInfo: ''
    }),
    actions: {
      // 登录
      login(userInfo) {
        const userCode = userInfo.userCode
        const password = userInfo.password
        return new Promise((resolve, reject) => {
          login(userCode, password).then(res => {
            const { code, data, msg } = res
            if (code == 200) {
              const { Authorization } = data
              TokenUtils.setAuthorization(Authorization)
              this.token = Authorization
            } else {
              ElMessage.error(msg)
            }
            resolve()
          }).catch(error => {
            ElMessage.error(error)
            reject(error);
          })
        })
      },
      // 获取用户信息
      getInfo() {
        return new Promise((resolve, reject) => {
          getInfo().then(res => {
            const { code, data, msg } = res
            this.userInfo = data
            if (code === 200) {
              resolve(data)
            } else {
              reject(msg)
            }
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 退出系统
      logOut() {
        return new Promise((resolve, reject) => {
          logout(this.token).then(() => {
            this.token = ''
            this.roles = []
            this.permissions = []
            TokenUtils.removeAuthorization()
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      /** 获取密钥 */
      getSecretKey() {
        return new Promise((resolve, reject) => {
          getAuth().then(res => {
            const { code, data, msg } = res
            if (code === 200) {
              resolve(data)
            } else {
              reject(msg)
            }
          }).catch(error => {
            reject(error)
          })
        })
      },
    }
  })

export default useUserStore
